<template>
  <div class="dia">
    <el-dialog
      v-el-drag-dialog
      :title="title"
      :visible.sync="visible"
      width="1024px"
      :before-close="handleClose"
      @closed="reset"
    >
      <div class="btn-col">
        <el-button v-for="i in btnList" :key="i.id" type="primary" :icon="i.icon" @click="onPush(i.id)">{{ i.txt }}</el-button>
      </div>
      <div class="ext-table">
        <el-card v-for="(item, index) in cardList" :key="item.orderNo" :shadow="isStyleId === item.orderNo ? 'always' : 'never'" style="margin-bottom: 20px;" :body-style="isStyleId === item.orderNo ? bodyStyle : '' " @click.native="onBox(item)">
          <template v-if="item.endEdit">
            <div class="card-title">
              <h2>{{ item.itemName }}</h2>
              <div class="card-title-btn">
                <el-button v-for="i in btnsList" :key="i.id" @click.stop="toPush(item, i.id, index)">{{ i.txt }}</el-button>
              </div>
            </div>
            <div class="edit-table-tab">
              <lb-table
                ref="lbTable"
                border
                highlight-current-row
                element-loading-text="加载中"
                :column="tableData.column"
                :data="item.detailList"
              />
            </div>
          </template>
          <template v-else>
            <!-- 编辑组件 -->
            <EditTable ref="edittable" @cancelEdit="cancelEdit" @saveEdit="saveEdit" />
          </template>
        </el-card>
        <el-card v-if="isNewCrad" :shadow="isNewCrad ? 'always' : 'never'" :body-style="bodyStyle">
          <!-- 编辑组件 -->
          <EditTable ref="edittable" @cancelEdit="cancelEdit" @saveEdit="saveEdit" />
        </el-card>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">
          关闭
        </el-button>
        <el-button :loading="$loadingPlugin.add" type="primary" @click="success">
          保存
        </el-button>
      </div>
    </el-dialog>
    <CopyAdd ref="copyadd" @onCopyAdd="open" />
  </div>
</template>

<script>
  import { checkConfigInquire, checkConfigList, checkConfigSave } from '@/api'
  import EditTable from './EditTable'
  import CopyAdd from './CopyAdd'

  export default {
    name: 'waterconfig',
    components: {
      EditTable,
      CopyAdd
    },
    data() {
      return {
        btnList: [
          { icon: 'el-icon-circle-plus-outline', txt: '新增', id: 1 },
          { icon: 'el-icon-circle-plus-outline', txt: '复制添加', id: 2 },
          { icon: 'el-icon-set-up', txt: '同步上级新增', id: 3 }
        ],
        visible: false,
        isNewCrad: false, // 是否新增
        newCradData: {},
        newTreeData: {},
        rawData: {}, // 上一次修改完成的数据
        initData: {}, // 初始数据
        newCradList: { // 增加新数据源
          itemId: 0,
          itemName: '',
          checkType: '',
          itemType: 1,
          orgId: '',
          orgName: '',
          orgSNNo: '',
          endEdit: true,
          csmType: '',
          orderNo: '',
          detailList: [
            {
              itemDetailId: 0,
              itemDetailName: '',
              itemId: 0,
              itemName: '',
              isChecked: 1,
              itemType: 1,
              orderNo: 1
            }
          ]
        },
        isStyleId: '',
        title: '',
        btnsList: [
          { txt: '编辑', id: 1 },
          { txt: '删除', id: 2 },
          { txt: '上移', id: 3 },
          { txt: '下移', id: 4 },
          { txt: '最前', id: 5 },
          { txt: '最后', id: 6 }
        ],
        bodyStyle: {},
        cardList: [],
        tableData: {
          column: [
            {
              prop: 'itemDetailName',
              label: '选项说明'
            },
            {
              prop: 'csmName',
              label: '默认',
              render: (h, { row, $index }) => {
                return (
                  <div>
                    { row.itemType === 1 && <el-checkbox></el-checkbox>}
                    { row.itemType === 3 && <el-radio></el-radio>}
                  </div>
                )
              }
            }
          ]
        }
      }
    },
    async created() {},
    methods: {
      async open(cardVal, treeVal) {
        console.log('数据', cardVal, treeVal)
        this.newCradData = cardVal
        this.newTreeData = treeVal
        this.title = `${this.newCradData.title}--->数据来源:${treeVal.orgName}`
        // 初始化增加数据
        this.newCradList.checkType = cardVal.id
        this.newCradList.csmType = cardVal.value
        this.newCradList.orgId = treeVal.orgId
        this.newCradList.orgName = treeVal.orgName
        this.newCradList.orgSNNo = treeVal.orgSNNo
        const { data } = await checkConfigInquire({
          csmType: cardVal.value,
          checkType: cardVal.id,
          orgId: treeVal.orgId,
          orgName: treeVal.orgName,
          orgSNNo: treeVal.orgSNNo
        })
        const endEdit = true // 如果为false打开编辑框 如果为true关闭编辑框
        var orderNo = 0 // 排序号
        this.cardList = data.map(item => {
          orderNo++
          return { ...item, endEdit, orderNo }
        })
        // 存储一份原数据
        this.rawData = this.deepClone(this.cardList)
        // 存储一份初始数据
        this.initData = this.deepClone(this.cardList)
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
        })
      },
      async success() {
        const me = this
        // 点击编辑之前判断是否有其他编辑项
        const flag = me.cardList.every(item => item.endEdit !== false)
        const isFlag = flag === true && me.newCradList.endEdit === true
        if (isFlag) {
          if (me.cardList.length) {
            // 请求接口
            const { status } = await checkConfigSave(me.cardList)
            if (status === 200) {
              me.$message({
                type: 'success',
                message: '保存安检数据成功!'
              })
              return new Promise(resolve => {
                this.resolve = resolve
                this.visible = false
              })
            }
          } else {
            me.$message({
              message: '请增加安检项',
              type: 'warning'
            })
          }
        } else {
          me.$message({
            message: '存在未结束编辑的安检项',
            type: 'warning'
          })
        }
      },
      reset() {
        this.init()
      },
      handleClose() {
        this.visible = false
        var dialogBody = document.getElementsByClassName('el-dialog__body')[0]
        dialogBody.scrollTop = 0
      },
      // 按钮事件
      toPush(val, type, index) {
        const me = this
        const obj = {
          // 编辑
          1: (val) => {
            // 点击编辑之前判断是否有其他编辑项
            const flag = me.cardList.every(item => item.endEdit !== false)
            const isFlag = flag === true && me.newCradList.endEdit === true
            if (isFlag) {
              me.onBox(val)
              me.cardList.map(item => {
                val.orderNo === item.orderNo ? item.endEdit = false : item.endEdit = true
              })
              // 在下一次DOM更新循环结束之后执行回调
              me.$nextTick(() => {
                me.$refs.edittable[0].open(val)
              })
            } else {
              me.$message({
                message: '存在未结束编辑的安检项',
                type: 'warning'
              })
            }
          },
          // 删除
          2: (val) => {
            this.cardList = this.cardList.filter(item => {
              return item.orderNo !== val.orderNo
            })
          },
          // 上移
          3: (val, index) => {
            if (index !== 0) {
              const topData = this.cardList[index - 1 ] // 获取上一条数据
              this.cardList[index] = topData // 把一条数据复制给当前数据
              this.cardList[index - 1] = val // 把当前数据复制给上一个数据
              this.cardList = [...this.cardList] // 从新复制数据
            }
          },
          // 下移
          4: (val, index) => {
            if (index !== this.cardList.length - 1) {
              const topData = this.cardList[index + 1 ]
              this.cardList[index] = topData
              this.cardList[index + 1] = val
              this.cardList = [...this.cardList]
            }
          },
          // 最前
          5: (val, index) => {
            if (index !== 0) {
              const topData = this.cardList[0]
              this.cardList[index] = topData
              this.cardList[0] = val
              this.cardList = [...this.cardList]
            }
          },
          // 最后
          6: (val, index) => {
            if (index !== this.cardList.length - 1) {
              const topData = this.cardList[ this.cardList.length - 1 ]
              this.cardList[index] = topData
              this.cardList[this.cardList.length - 1] = val
              this.cardList = [...this.cardList]
            }
          }
        }
        obj[type](val, index)
      },
      onPush(type) {
        const me = this
        const obj = {
          // 增加
          1: () => {
            // 点击编辑之前判断是否有其他编辑项
            const flag = me.cardList.every(item => item.endEdit !== false)
            const isFlag = flag === true && me.newCradList.endEdit === true
            if (isFlag) {
              me.isStyleId = ''
              me.bodyStyle = {
                'border': '1px solid #617ff8',
                'box-shadow': '0px 3px 6px 0px undef'
              }
              me.isNewCrad = true
              me.newCradList.endEdit = false
              this.newCradList.orderNo = me.cardList[ me.cardList.length - 1 ].orderNo
              this.newCradList.orderNo++
              // 在下一次DOM更新循环结束之后执行回调
              me.$nextTick(() => {
                me.$refs.edittable.open(me.deepClone(me.newCradList), me.isNewCrad)
                this.$refs.edittable.$el.scrollIntoView() // 增加元素 保持滚动条再底部
              })
            } else {
              me.$message({
                message: '存在未结束编辑的安检项',
                type: 'warning'
              })
            }
          },
          // 复制添加
          2: async() => {
            me.$refs.copyadd.open(me.newCradData, me.newTreeData)
          },
          // 同步上级新增
          3: async() => {
            const { status } = await checkConfigList({
              orgId: this.newTreeData.orgId,
              csmType: this.newCradData.value,
              checkType: this.newCradData.id
            })
            if (status === 200) {
              // 重新复制初始数据
              this.cardList = this.deepClone(this.initData)
            }
          }
        }
        obj[type]()
      },
      // 取消编辑
      cancelEdit(tableData, isBtnEdit) {
        console.log('tableData', tableData, 'isBtnEdit', isBtnEdit)
        this.init()
        this.cardList.map(item => item.endEdit = true)
        // 处理编辑按钮逻辑
        if (isBtnEdit) {
          this.cardList = this.cardList.filter(item => {
            return item.itemId !== tableData.itemId
          })
          // 重新复制上一次修改完成的数据
          this.rawData = this.cardList
        } else {
          // 重新复制上一次修改完成的数据
          this.cardList = this.deepClone(this.rawData)
        }
      },
      // 完成编辑
      saveEdit(obj) {
        var id = 1
        this.init()
        const flag = this.cardList.every(item => item.itemId !== obj.data.itemId)
        if (flag) {
          this.cardList.push(obj.data)
        } else {
          // 走到这里说明是新增的数据和新增的旧数据
          const flag = this.cardList.every(item => item.orderNo !== obj.data.orderNo)
          if (flag) {
            this.cardList.push(obj.data)
          }
        }
        this.cardList.map(item => {
          item.endEdit = true
          item.orderNo = id++
        })
        // 存储一份上一次修改完成的数据
        this.rawData = this.deepClone(this.cardList)
      },
      // 卡片点击
      onBox(val) {
        // 改变选中的样式
        this.isStyleId = val.orderNo
        this.bodyStyle = {
          'border': '1px solid #617ff8',
          'box-shadow': '0px 3px 6px 0px undef'
        }
      },
      // 初始化
      init() {
        this.newCradList.endEdit = true
        this.isStyleId = ''
        this.isNewCrad = false
        this.bodyStyle = {}
      },
      // 深拷贝
      deepClone(target) {
        var result
        if (typeof target === 'object') {
          if (Array.isArray(target)) {
            result = []
            for (const i in target) {
              result.push(this.deepClone(target[i]))
            }
          } else if (target === null) {
            result = null
          } else if (target.constructor === RegExp) {
            result = target
          } else {
            result = {}
            for (const i in target) {
              result[i] = this.deepClone(target[i])
            }
          }
        } else {
          result = target
        }
        return result
      }
    }
  }
</script>

<style lang="scss" scoped>
/deep/.el-dialog__body {
  padding-top: 0;
  margin-top: 0;
}
.btn-col {
  position: fixed;
  z-index: 1000;
  width: 944px;
  padding-top: 20px;
  padding-bottom: 20px;
  background: #fff;
}
.ext-table {
  padding-top: 72px;
  .card-title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20px;
    h2 {
      height: 20px;
      padding-left: 12px;
      margin: 0;
      font-family: Microsoft YaHei, Microsoft YaHei-Bold;
      font-size: 14px;
      font-weight: 700;
      line-height: 20px;
      color: #01999f;
      border-left: 4px solid #01999f;
    }
  }
}
</style>
